#! /bin/sh

do_install () 
{

# Delete disks partition ...
/bin/dd if=/dev/zero of=/dev/$disk count=128
sleep 1

# Tells fdisk to use the whole disk space
/sbin/fdisk -I $disk
sleep 1

# Disklabel stuff to initialize the disk
/sbin/disklabel -rw ${disk}s1 auto
sleep 1

# Define disk partitions.
modelo=/tmp/label.modelo
/sbin/disklabel -r ${disk}s1 > $modelo

# Figure out how much blocks it is still avaiable
total_blocks=`/sbin/disklabel -r ${disk}s1 | /usr/bin/tr -s ' ' | \
          /usr/bin/sed 's/^ //g' | /usr/bin/grep '^c: ' | \
          /usr/bin/cut -f2 -d' '`

# Defines the block number for every slice,1M = 1024*2 blocks (1block = 512B)
b_swap=`expr $swap \* 1024 \* 2`
b_root=`expr $total_blocks \- $b_swap`

# The base model to be used by disklabel
# size  offset fstype [ fsize bsize bps/cpg ]
echo "a: $b_root        0 4.2BSD 0 0 0"  >>  $modelo
echo "b: $b_swap  $b_root swap"          >>  $modelo 

# Create disks partitions and sets it as "bootavel"
/sbin/disklabel -R -B ${disk}s1 $modelo
sleep 1

# Filesystem for /
/sbin/newfs /dev/${disk}s1a
sleep 1

# disk mount 
mkdir -p /mnt
/sbin/mount /dev/${disk}s1a /mnt
sleep 1

# turns swap on
swapon /dev/${disk}s1b

# Copies LiveCD files to Hard Disk.
cd /mnt
for i in bin boot etc lib libexec root sbin usr var
do
  cp -Rvp /$i .
  sleep 1
done

mkdir -p /mnt/tmp
mkdir -p /mnt/dev
mkdir -p /mnt/proc

chmod 555 /mnt/proc /mnt/dev
chmod 777 /mnt/tmp
chmod -R 777 /mnt/var
chmod -R 755 /mnt/bin /mnt/boot /mnt/etc /mnt/lib /mnt/libexec /mnt/root /mnt/sbin /mnt/usr 


echo stairway > /mnt/usr/local/stairway/etc/platform

cp /.cshrc /mnt
cp /.profile /mnt
cp /COPYRIGHT /mnt
sed -e "s/{disk}/${disk}/g" /usr/local/stairway/tools/install/fstab.install > /mnt/etc/fstab

# The partition to be used for as / mount point
echo rootdev="${disk}s1a" >> /mnt/boot/loader.conf

cd /

sleep 1

# umount actual disk definitions
/sbin/umount /mnt

touch /tmp/install_ok
}

if [ -f /tmp/install_ok ] ; then
    echo "install completed."
    exit 0
fi

if [ "$#" -lt 2 ]; then
    echo "Usage: install.sh <disk> <swap>"
    echo ""
    echo "for example:"
    echo "install.sh ad0 256"
    echo "will setting 256MB for swap,"
    echo "and the the remaining disk free space for /"
    exit 1;
else
    disk=$1
    swap=$2
    do_install
fi
